/**
 * Author: grx
 * Description: 学习模块的"开始学习"子功能页面,包含"正向计时"和"倒计时"
 */
package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.example.parallelandroid.entity.StudyTimeRecord;
import com.example.parallelandroid.utils.CountdownTimeUtil;
import com.example.parallelandroid.utils.ForwardTimeUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.math.RoundingMode;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class StartStudyActivity extends AppCompatActivity implements NumberPicker.Formatter {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private Toolbar toolbar;
    private Button btnStartZheng;
    private TextView tvStudyTimeZheng;
    private LinearLayout linearTime1;
    private TextView tvHour1;
    private TextView tvMinute1;
    private TextView tvSecond1;
    private EditText edtDaoJiShi;
    private Button btnStartDao;
//    private Button btnTest; // 测试按钮
    private LinearLayout linearTime2;
    private TextView tvHour2;
    private TextView tvMinute2;
    private TextView tvSecond2;
    private TextView tvTips;
    private AlertDialog dialog;

    private int hour1;
    private int minute1;
    private int second1;
    private String timeStr1;

    private String hourStr2;
    private String minuteStr2;
    private int hour2;
    private int minute2;
    private int second2;
    private String timeStr2;
    private NumberPicker hourPicker;
    private NumberPicker minutePicker;
    private boolean isContinue = false;
    private boolean isDestroy = false;

    //与通知栏有关的sp
    private SharedPreferences clock;
    private boolean standup;
    private SharedPreferences studyData;
    private SharedPreferences user;
    private OkHttpClient okHttpClient;
    private SQLiteDatabase db;

    private Vibrator vibrator; // 震动类
    private MediaPlayer player; // 响铃

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_study);

        // 获取SharedPreferences
        user = getSharedPreferences("user", MODE_PRIVATE);
        studyData = getSharedPreferences("study_data", MODE_PRIVATE);
        //提醒有关
        clock = getSharedPreferences("Clock",MODE_PRIVATE);
        standup = clock.getBoolean("sitSwitch",false);
        // 获取震动操作的类
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        // 获取响铃操作的类
        player = new MediaPlayer();
        try {
            player.setDataSource(this, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)); // 设置音频：使用通知声音
            player.prepare(); // 让MediaPlayer真正去装载音频文件
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 在程序内部文件夹中创建数据库文件
        String path = getFilesDir().getAbsolutePath() + "/database";
        File file = new File(path);
        if (!file.exists()) {
            try {
                // 创建文件
                boolean mkdirs = file.mkdirs();
                if (mkdirs) {
                    Constant.logger.info("首次运行app,创建database目录成功");
                }
            } catch (Exception e) {
                Constant.logger.warn("创建database目录失败", e);
            }
        }
        MyDBHelper myDBHelper = new MyDBHelper(this.getApplicationContext(), "studyRecord.db", null, 1);
        db = myDBHelper.getWritableDatabase(); // 打开数据库

        // 获取控件对象
        getViews();

        // 显示控件
        showViews();

        // 弹窗展示使用注意点
        showTips();

        // 为ToolBar添加返回键
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("开始学习");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 添加默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); // 设置返回键可用
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 返回
                Constant.logger.info("finish StartStudyActivity");
            }
        });

        // 给两个"开始"按钮绑定监听器
        setListeners();

        // 给edtDaoJiShi绑定点击事件监听器
        edtDaoJiShi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = new AlertDialog.Builder(StartStudyActivity.this).create();
                dialog.show();
                dialog.getWindow().setContentView(R.layout.time_dialog);

                // 获取NumberPicker
                hourPicker = ((NumberPicker) dialog.getWindow().findViewById(R.id.np_hour));
                minutePicker = ((NumberPicker) dialog.getWindow().findViewById(R.id.np_minute));
                // 初始化NumberPicker
                initNumberPicker();
                hourPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        StartStudyActivity.this.hour2 = newVal;
                    }
                });

                minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        StartStudyActivity.this.minute2 = newVal;
                    }
                });

                // 给弹框的"确定"按钮绑定监听器
                dialog.getWindow().findViewById(R.id.btn_timeSure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StartStudyActivity.this.minute2 < 10) {
                            edtDaoJiShi.setText(StartStudyActivity.this.hour2 + " 小时 0" + StartStudyActivity.this.minute2 + " 分钟");
                        } else {
                            edtDaoJiShi.setText(StartStudyActivity.this.hour2 + " 小时 " + StartStudyActivity.this.minute2 + " 分钟");
                        }
                        // 获取edtDaoJiShi的值
                        timeStr2 = edtDaoJiShi.getText().toString();
                        Constant.logger.info("确定倒计时时长为: " + timeStr2);

                        if (timeStr2 != null && !timeStr2.equals("")) {
                            if (timeStr2.length() <= 10) {
                                hourStr2 = timeStr2.substring(0, 7).split(" 小时 ")[0];
                                minuteStr2 = timeStr2.substring(0, 7).split(" 小时 ")[1];
                                if (minuteStr2.charAt(1) == '0') {
                                    minuteStr2 = minuteStr2.charAt(1) + "";
                                }
                            }
                        }

                        dialog.dismiss();
                    }
                });

                // 给弹框的"重置"按钮绑定监听器
                dialog.getWindow().findViewById(R.id.btn_timeReset).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Constant.logger.info("重置倒计时时长");
                        hourPicker.setValue(0);
                        minutePicker.setValue(0);
                        StartStudyActivity.this.hour2 = 0;
                        StartStudyActivity.this.minute2 = 0;
                    }
                });
                // 给弹框的"取消"按钮绑定监听器
                dialog.getWindow().findViewById(R.id.btn_timeCancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Constant.logger.info("取消倒计时时长");
                        dialog.dismiss();
                    }
                });
            }
        });

    }

    /**
     * 弹窗展示使用注意项
     */
    private void showTips() {
        //1创建Builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(StartStudyActivity.this);
        //2设置属性参数
        // 设置标题 提示文本、确定及取消按钮
        builder.setTitle("温馨提示")
                .setMessage("1.单次学习时长须大于20分钟才会被有效记录,否则无效\n" +
                        "2.学习计时开始后，请不要离开本页面，否则计时将强制停止\n" +
                        "3.倒计时单次学习最大时长为6h59min，请注意劳逸结合喔~")
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        //3创建AlertDialog对象
        AlertDialog dialog=builder.create();
        //4显示对话框
        dialog.show();
    }

    /**
     * 显示控件
     */
    private void showViews() {
        if (studyData.getBoolean("isStartDao", false)) {
            linearTime2.setVisibility(View.VISIBLE);
            edtDaoJiShi.setVisibility(View.INVISIBLE);
            btnStartDao.setText("结束");
        } else {
            linearTime2.setVisibility(View.INVISIBLE);
            edtDaoJiShi.setVisibility(View.VISIBLE);
            btnStartDao.setText("开始");
        }
    }

    /**
     * 给两个"开始"按钮绑定监听器
     */
    private void setListeners() {
        MyListener myListener = new MyListener();
        btnStartZheng.setOnClickListener(myListener);
        btnStartDao.setOnClickListener(myListener);
//        btnTest.setOnClickListener(myListener);
    }

    /**
     * 初始化NumberPicker
     */
    private void initNumberPicker() {
//        hourPicker.setFormatter(this);
        hourPicker.setMaxValue(6);
        hourPicker.setMinValue(0);
        if (hourStr2 != null) {
            if (!hourStr2.equals("")) {
                hourPicker.setValue(Integer.parseInt(hourStr2));
            }
        }

        minutePicker.setFormatter(this);
        minutePicker.setMaxValue(59);
        minutePicker.setMinValue(0);
        if (minuteStr2 != null) {
            if (!minuteStr2.equals("")) {
                minutePicker.setValue(Integer.parseInt(minuteStr2));
            }
        }
        Constant.logger.info("初始化NumberPicker");
    }

    /**
     * 获取控件对象
     */
    private void getViews() {
        toolbar = findViewById(R.id.toolbar);
        btnStartZheng = findViewById(R.id.btn_startZheng);
        tvStudyTimeZheng = findViewById(R.id.tv_studyTimeZheng);
        linearTime1 = findViewById(R.id.linear_time1);
        tvHour1 = findViewById(R.id.tv_hour1);
        tvMinute1 = findViewById(R.id.tv_minute1);
        tvSecond1 = findViewById(R.id.tv_second1);
        edtDaoJiShi = findViewById(R.id.edt_daojishi);
        btnStartDao = findViewById(R.id.btn_startDao);
//        btnTest = findViewById(R.id.btn_test);
        linearTime2 = findViewById(R.id.linear_time2);
        tvHour2 = findViewById(R.id.tv_hour2);
        tvMinute2 = findViewById(R.id.tv_minute2);
        tvSecond2 = findViewById(R.id.tv_second2);
        tvTips = findViewById(R.id.tv_tips);
    }

    @Override
    public String format(int value) {
        String tmpStr = String.valueOf(value);
        if (value < 10) {
            tmpStr = "0" + tmpStr;
        }
        return tmpStr;
    }

    private class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            SharedPreferences.Editor editor = studyData.edit();
            switch (v.getId()) {
                case R.id.btn_startZheng:
                    if (studyData.getBoolean("isStartDao", false)) {//倒计时已经开始
                        Toast.makeText(StartStudyActivity.this, "倒计时还在进行中喔~", Toast.LENGTH_LONG).show();
                    } else {//倒计时未开始或已经结束
                        if (studyData.getBoolean("isStartZheng", false)) {
                            btnStartZheng.setText("开始");
                            editor.putBoolean("isStartZheng", false);
                            tvStudyTimeZheng.setVisibility(View.VISIBLE);
                            linearTime1.setVisibility(View.INVISIBLE); // 设置倒计时文本不可见
                            tvTips.setVisibility(View.INVISIBLE); // 设置提示不可见

                            // 关闭正向计时
                            ForwardTimeUtil.stopTimer();
                            // 计算本次学习的小时、分钟、秒
                            calculateLearningDurationZheng();
                            // 将本次学习时长显示到页面上
                            timeStr1 = "本次学习时长: " + hour1 + " 小时 " + minute1 + " 分钟 " + second1 + " 秒";
                            tvStudyTimeZheng.setText(timeStr1);
                            Constant.logger.info("正向计时结束," + timeStr1);

                            // 判断学习时间是否超过20分钟
                            if (hour1*3600+minute1*60+second1 >= 20 * 60) {
                                Constant.logger.info("正向计时时长超过10秒,数据有效");
                                // 生成新的学习记录对象 StudyTimeRecord
                                StudyTimeRecord zhengRecord = createStudyTimeRecord(hour1, minute1, second1);
                                // 向服务端传输学习记录数据
                                sendRecord2server(zhengRecord);
                                // 将学习记录存储到本地studyRecord.db文件中
                                saveRecord(zhengRecord);
                            } else {
                                Toast.makeText(getBaseContext(), "学习时间不足20分钟,本次计时无效", Toast.LENGTH_LONG).show();
                                Constant.logger.info("正向计时学习时间不足10秒,数据无效");
                            }
                        } else {
                            btnStartZheng.setText("结束");
                            editor.putBoolean("isStartZheng", true);
                            tvStudyTimeZheng.setVisibility(View.INVISIBLE);
                            linearTime1.setVisibility(View.VISIBLE); // 设置倒计时文本可见
                            tvTips.setVisibility(View.VISIBLE); // 设置提示可见
                            // 开始正向计时
                            ForwardTimeUtil.startTimer(true, tvHour1, tvMinute1, tvSecond1);
                            Constant.logger.info("正向计时开始");
                        }
                        editor.commit();
                    }
                    break;
                case R.id.btn_startDao:
                    if (studyData.getBoolean("isStartZheng", false)) {//正向计时还未结束
                        Toast.makeText(StartStudyActivity.this, "正向计时还在进行中喔~", Toast.LENGTH_LONG).show();
                    } else {//正向计时未开始或已经结束
                        if (studyData.getBoolean("isStartDao", false)) {
                            btnStartDao.setText("开始");
                            editor.putBoolean("isStartDao", false);
                            editor.commit();
                            edtDaoJiShi.setVisibility(View.VISIBLE); // 设置文本框可见
                            linearTime2.setVisibility(View.INVISIBLE); // 设置倒计时文本不可见
                            tvTips.setVisibility(View.INVISIBLE); // 设置提示不可见
                            // 计算本次学习的小时、分钟、秒
                            int difference = calculateLearningDurationDao();
                            // 将本次学习时长显示到页面上
                            timeStr2 = "本次学习时长: " + hour2 + " 小时 " + minute2 + " 分钟 " + second2 + " 秒";
                            edtDaoJiShi.setText(timeStr2);
                            Constant.logger.info("倒计时结束," + timeStr2);

                            // 关闭倒计时,同时关闭响铃或震动
                            CountdownTimeUtil.stopCountdown();

                            // 判断学习时长是否超过20分钟
                            if (difference >= 20 * 60) {
                                Constant.logger.info("倒计时时长超过20分钟,数据有效 " + hour2 + ":" + minute2 + ":" + second2);
                                // 生成新的学习记录对象 StudyTimeRecord
                                StudyTimeRecord daoRecord = createStudyTimeRecord(hour2, minute2, second2);
                                // 向服务端传输学习记录数据
                                sendRecord2server(daoRecord);
                                // 将学习记录存储到本地studyRecord.db文件中
                                saveRecord(daoRecord);
                            } else {
                                Toast.makeText(getBaseContext(), "学习时间不足20分钟,本次计时无效", Toast.LENGTH_LONG).show();
                                Constant.logger.info("倒计时学习时间不足20分钟,数据无效");
                            }
                        } else {
                            if (timeStr2 == null || timeStr2.equals("")) {
                                Toast.makeText(StartStudyActivity.this, "请先选择倒计时时长喔~", Toast.LENGTH_LONG).show();
                            } else {
                                if (timeStr2.length() <= 10) {// 已重新选择好倒计时时长
                                    int time = Integer.parseInt(hourStr2)*60 + Integer.parseInt(minuteStr2); //选择的倒计时时长(分钟)
                                    if (time < 20 && !isContinue) {//倒计时时长<20min
                                        // 弹窗提醒
                                        AlertDialog builder = new AlertDialog.Builder(StartStudyActivity.this)
                                                .setTitle("提示")
                                                .setMessage("倒计时时长不足20分钟，本次计时将无效，您仍然要继续吗？")
                                                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        isContinue = true;
                                                    }
                                                })
                                                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        isContinue = false;
                                                    }
                                                })
                                                .show();
                                    } else {//倒计时时长>=20min
                                        btnStartDao.setText("结束");
                                        editor.putBoolean("isStartDao", true);
                                        editor.commit();
                                        edtDaoJiShi.setVisibility(View.INVISIBLE); // 设置文本框不可见
                                        linearTime2.setVisibility(View.VISIBLE); // 设置倒计时文本可见
                                        tvTips.setVisibility(View.VISIBLE); // 设置提示可见
                                        // 判断用户设置的手机模式
                                        AudioManager audio = (AudioManager) getSystemService(AUDIO_SERVICE);
                                        switch (audio.getRingerMode()) {
                                            case AudioManager.RINGER_MODE_SILENT: //静音
                                                break;
                                            case AudioManager.RINGER_MODE_NORMAL: //响铃
                                                // 开始倒计时
                                                CountdownTimeUtil.startCountdown(player, vibrator, true, StartStudyActivity.this.hour2, StartStudyActivity.this.minute2, 0, tvHour2, tvMinute2, tvSecond2);
                                                Constant.logger.info("响铃模式下 倒计时开始");
                                                break;
                                            case AudioManager.RINGER_MODE_VIBRATE: //震动
                                                // 开始倒计时
                                                CountdownTimeUtil.startCountdown(vibrator, true, StartStudyActivity.this.hour2, StartStudyActivity.this.minute2, 0, tvHour2, tvMinute2, tvSecond2);
                                                Constant.logger.info("震动模式下 倒计时开始");
                                                break;
                                        }
                                    }
                                } else {// 未重新选择倒计时时长
                                    Toast.makeText(StartStudyActivity.this, "请重新选择倒计时时长喔~", Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                    }
                    break;
                /*case R.id.btn_test:
                    if (studyData.getBoolean("isTest", false)) {//正在进行中
                        btnTest.setText("铃声震动测试");
                        editor.putBoolean("isTest", false);
                        editor.commit();
                        edtDaoJiShi.setVisibility(View.VISIBLE); // 设置文本框可见
                        linearTime2.setVisibility(View.INVISIBLE); // 设置倒计时文本不可见
                        tvTips.setVisibility(View.INVISIBLE); // 设置提示不可见

                        // 关闭倒计时,同时关闭响铃或震动
                        CountdownTimeUtil.stopCountdown();
                    } else {// 计时结束
                        btnTest.setText("结束");
                        editor.putBoolean("isTest", true);
                        editor.commit();
                        edtDaoJiShi.setVisibility(View.INVISIBLE); // 设置文本框不可见
                        linearTime2.setVisibility(View.VISIBLE); // 设置倒计时文本可见
                        tvTips.setVisibility(View.VISIBLE); // 设置提示可见
                        // 判断用户设置的手机模式
                        AudioManager audio = (AudioManager) getSystemService(AUDIO_SERVICE);
                        switch (audio.getRingerMode()) {
                            case AudioManager.RINGER_MODE_SILENT: //静音
                                break;
                            case AudioManager.RINGER_MODE_NORMAL: //响铃
                                // 开始倒计时
                                CountdownTimeUtil.startCountdown(player, vibrator, true, 0, 0, 3, tvHour2, tvMinute2, tvSecond2);
                                Constant.logger.info("响铃模式下 倒计时开始");
                                break;
                            case AudioManager.RINGER_MODE_VIBRATE: //震动
                                // 开始倒计时
                                CountdownTimeUtil.startCountdown(vibrator, true, 0, 0, 3, tvHour2, tvMinute2, tvSecond2);
                                Constant.logger.info("震动模式下 倒计时开始");
                                break;
                        }
                    }
                    break;*/
            }
        }
    }

    /**
     * 计算倒计时的学习时长
     * @return 学习时长(秒数)
     */
    private int calculateLearningDurationDao() {
        timeStr2 = edtDaoJiShi.getText().toString();
        if (timeStr2 != null && !timeStr2.equals("")) {
            hourStr2 = timeStr2.substring(0, 7).split(" 小时 ")[0];
            minuteStr2 = timeStr2.substring(0, 7).split(" 小时 ")[1];
            if (minuteStr2.charAt(0) == '0') {
                minuteStr2 = minuteStr2.charAt(1) + "";
            }
        }
        int count = Integer.parseInt(hourStr2) * 60 * 60 + Integer.parseInt(minuteStr2) * 60;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (tvHour2.getText().toString() != null && !tvHour2.getText().toString().equals("")) {
            hour = Integer.parseInt(tvHour2.getText().toString());
        }
        if (tvMinute2.getText().toString() != null && !tvMinute2.getText().toString().equals("")) {
            minute = Integer.parseInt(tvMinute2.getText().toString());
        }
        if (tvSecond2.getText().toString() != null && !tvSecond2.getText().toString().equals("")) {
            second = Integer.parseInt(tvSecond2.getText().toString());
        }
        int nowCount = hour * 60 * 60 + minute * 60 + second;
        int difference = count - nowCount;
        if (difference >= 60) {
            minute2 = difference / 60;   //取整
            second2 = difference % 60;   //取余
        } else {
            hour2 = 0;
            minute2 = 0;
            second2 = difference;
        }
        if (minute2 >= 60) {
            hour2 = minute2 / 60;
            minute2 = minute2 % 60;
        }
        return difference;
    }

    /**
     * 生成一个学习记录对象
     * @param hour 小时
     * @param minute 分钟
     * @param second 秒
     * @return StudyTimeRecord
     */
    private StudyTimeRecord createStudyTimeRecord(int hour, int minute, int second) {
        Date studyDate = new Date(System.currentTimeMillis());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String userDateId = user.getString("userId", "userId") + fmt.format(studyDate);
        // 保留两位小数
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        // 四舍五入
        nf.setRoundingMode(RoundingMode.UP);
        String studyTimeStr = nf.format((hour*60*60 + minute*60 + second) / 3600d);
        double studyTime = Double.parseDouble(studyTimeStr);
        StudyTimeRecord record = new StudyTimeRecord(userDateId, user.getString("userId", "userId"), studyDate, studyTime);
        return record;
    }

    /**
     * 计算正向计时的学习时长
     */
    private void calculateLearningDurationZheng() {
        if (tvHour1.getText().toString() != null && !tvHour1.getText().toString().equals("")) {
            hour1 = Integer.parseInt(tvHour1.getText().toString());
            //站立提醒通知（目前是大于0就通知）
            if (standup){
                if( (hour1>=0 && (studyData.getBoolean("isStartZheng",false)))) {
                    Intent intent = new Intent(this, ClockActivity.class);
                    PendingIntent pendingIntent =  PendingIntent.getActivity(StartStudyActivity.this, 0, intent, 0);

                    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                        NotificationChannel channel = new NotificationChannel("Message", "通知", NotificationManager.IMPORTANCE_HIGH);
                        manager.createNotificationChannel(channel);
                    }
                    Notification notification = new NotificationCompat.Builder(this,"Message")
                            .setContentText("您已经学习很久了，休息一下吧")
                            .setContentTitle("站立提醒（点击跳转到设置关闭）")
                            .setAutoCancel(true)
                            .setSmallIcon(R.mipmap.jiayou)
                            .setContentIntent(pendingIntent)
                            .build();
                    manager.notify(1,notification);
                }
            }else {

            }
        } else {
            hour1 = 0;
        }
        if (tvMinute1.getText().toString() != null && !tvMinute1.getText().toString().equals("")) {
            minute1 = Integer.parseInt(tvMinute1.getText().toString());
        }
        if (tvSecond1.getText().toString() != null && !tvSecond1.getText().toString().equals("")) {
            second1 = Integer.parseInt(tvSecond1.getText().toString());
        }
    }

    /**
     * 向服务端传输学习记录数据
     * @param record 新的学习记录对象
     */
    private void sendRecord2server(StudyTimeRecord record) {
        Constant.logger.info("开始向服务端传输学习记录数据 " + record.toString());

        // 将daoRecord转成JSON对象
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String studyJson = gson.toJson(record);

        okHttpClient = new OkHttpClient();
        // 创建请求体对象
        RequestBody requestBody = RequestBody.create(JSON, studyJson);
        // 创建请求对象
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "studyTimeRecord/createRecord")
                .post(requestBody)
                .build();
        // 发送请求，获取响应
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("向服务端传输学习记录: 失败", e);
                if (!isDestroy) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            // 此处执行UI操作
                            Toast.makeText(StartStudyActivity.this, "学习记录上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    String json = response.body().string();
                    JSONObject jsonObject = new JSONObject(json);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                    double intelligence = jsonObject.getDouble("data");
                    if (!isDestroy) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // 保留两位小数
                                NumberFormat nf = NumberFormat.getNumberInstance();
                                nf.setMaximumFractionDigits(2);
                                // 四舍五入
                                nf.setRoundingMode(RoundingMode.UP);
                                Toast.makeText(StartStudyActivity.this, "您的智力提升" + nf.format(intelligence) + "点,再接再厉喔~", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }

    /**
     * 将学习记录存储到本地studyRecord.db文件中
     * @param record 新的学习记录对象
     */
    private void saveRecord(StudyTimeRecord record) {
        Constant.logger.info("开始将学习记录存入本地studyRecord.db " + record.toString());
        ContentValues values = new ContentValues();
        values.put("userId", record.getUserId());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String studyDate = fmt.format(record.getStudyDate());
        values.put("studyDate", studyDate);
        // 保留两位小数
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        // 四舍五入
        nf.setRoundingMode(RoundingMode.UP);
        String studyTime = nf.format(record.getStudyTime());
        values.put("studyTime", Double.parseDouble(studyTime));
        try {
            long rowId = db.insert("studyRecord", null, values);
            Constant.logger.info("向本地存入学习记录成功,新插入记录的id值: " + rowId);
        } catch (Exception e) {
            Constant.logger.warn("向本地存入学习记录失败", e);
        }

    }

    /**
     * 计时期间用户中途退出，页面销毁时回调
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDestroy = true;
        SharedPreferences.Editor editor = studyData.edit();
        if (studyData.getBoolean("isStartZheng", false)) {
            editor.putBoolean("isStartZheng", false);
            editor.commit();
            // 停止正向计时
            ForwardTimeUtil.stopTimer();
            Constant.logger.warn("计时期间用户退出页面, 正向计时中断");

            // 计算本次学习的小时、分钟、秒
            calculateLearningDurationZheng();
            Constant.logger.info("正向计时结束,本次学习时长: " + hour1 + " 小时 " + minute1 + " 分钟 " + second1 + " 秒");
            // 判断学习时间是否超过20分钟
            if (hour1*3600+minute1*60+second1 >= 20 * 60) {
                Log.e("正向计时 向数据库传数据", hour1 + ":" + minute1 + ":" + second1);
                Constant.logger.info("正向计时时长超过10秒,数据有效");
                // 生成新的学习记录对象 StudyTimeRecord
                StudyTimeRecord zhengRecord = createStudyTimeRecord(hour1, minute1, second1);
                // 向服务端传输学习记录数据
                sendRecord2server(zhengRecord);
                // 将学习记录存储到本地studyRecord.db文件中
                saveRecord(zhengRecord);
            } else {
                Constant.logger.info("正向计时学习时间不足20分钟,数据无效");
            }
        }

        if (studyData.getBoolean("isStartDao", false)) {
            editor.putBoolean("isStartDao", false);
            editor.commit();
            // 停止倒计时
            CountdownTimeUtil.stopCountdown();
            Constant.logger.info("计时期间用户退出页面, 倒计时中断");
            // 计算本次学习的小时、分钟、秒
            int difference = calculateLearningDurationDao();
            Constant.logger.info("倒计时结束,本次学习时长: " + hour2 + " 小时 " + minute2 + " 分钟 " + second2 + " 秒");
            // 判断学习时长是否超过20分钟
            if (difference >= 20 * 60) {
                // 生成新的学习记录对象 StudyTimeRecord
                StudyTimeRecord daoRecord = createStudyTimeRecord(hour2, minute2, second2);
                // 向服务端传输学习记录数据
                sendRecord2server(daoRecord);
                // 将学习记录存储到本地studyRecord.db文件中
                saveRecord(daoRecord);
            } else {
                Constant.logger.info("倒计时学习时间不足20分钟,数据无效");
            }
        }
    }


}